using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdmin.Models;
using AvalonAdminDto.CarParts.CarPartsDtos;
using AvalonAdminDto.CarParts.CarPartsTypeDtos;
using AvalonAdminDto.CarType.VehicleSeriesDtos;
using AvalonAdminDto.Common;
using AvalonAdminDto.Sys.AdminDtos;
using D.UtilCore.Dtos;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace AvalonAdmin.Pages.CarParts.ViewModels.CarParts
{
    /// <summary>
    /// 配件修改视图模型
    /// </summary>
    public class CarPartsModifyViewModel : BaseModifyViewModel
    {
        #region 页面属性及初始化数据

        private string? _id;

        private RepCarParts _currentCarParts;
        private ObservableCollection<RepVehicleSeries> _repVehicleSeriesList;
        private ObservableCollection<RepCarPartsType> _repCarPartsTypeList;

        public CarPartsModifyViewModel(string? id = null, ViewStatus? viewStatus = ViewStatus.Add)
        {
            _id = id;
            _currentCarParts = new RepCarParts();
            SetupFormStatus(viewStatus);

            RepVehicleSeriesList = new ObservableCollection<RepVehicleSeries>();
            RepCarPartsTypeList = new ObservableCollection<RepCarPartsType>();

            LoadRelatedDataAsync();

            if (!string.IsNullOrEmpty(id))
            {
                _ = Task.Run(async () =>
                {
                    await QueryAsync();
                });
            }
        }
          
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="id">ID</param>
        public override async Task<bool> QueryAsync()
        {
            try
            {
                IsLoading = true;

                var res = await HttpHelper<RepCarParts>.GetAsync($"{ApiUrl.GetCarParts}/{_id}");
                if (res.Code == StatusCodeEnum.OK && res.Data != null)
                {
                    CurrentCarParts = res.Data;
                    OnPropertyChanged(nameof(Name));
                    OnPropertyChanged(nameof(EnglishName));
                    OnPropertyChanged(nameof(Code));
                    OnPropertyChanged(nameof(VehicleSeriesId));
                    OnPropertyChanged(nameof(CarPartsTypeId));
                    OnPropertyChanged(nameof(StartingDate));
                    OnPropertyChanged(nameof(EndingDate));
                    OnPropertyChanged(nameof(Image));
                    OnPropertyChanged(nameof(CustomField1));
                    OnPropertyChanged(nameof(CustomField2));
                    OnPropertyChanged(nameof(CustomField3));
                    OnPropertyChanged(nameof(CustomField4));
                    OnPropertyChanged(nameof(CustomField5));
                }
                else if (res.Code == StatusCodeEnum.Waring)
                {
                    ShowWarning(res.Msg);
                }
                else
                {
                    ShowError(res.Msg ?? "加载品牌数据失败");
                }
            }
            catch (Exception ex)
            {
                ShowError($"加载品牌数据失败：{ex.Message}");
            }
            return true;
        }

        /// <summary>
        /// 加载相关数据
        /// </summary>
        private async void LoadRelatedDataAsync()
        {
            await LoadVehicleSeriesListAsync();
            await LoadCarPartsTypeListAsync();
        }

        /// <summary>
        /// 加载车系列表
        /// </summary>
        private async Task LoadVehicleSeriesListAsync()
        {
            try
            {
                var response = await HttpHelper<List<RepVehicleSeries>>.GetAsync(ApiUrl.QueryVehicleSeriesList);
                if (response?.Code == StatusCodeEnum.OK && response.Data != null)
                {
                    RepVehicleSeriesList.Clear();
                    foreach (var item in response.Data)
                    {
                        RepVehicleSeriesList.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError($"加载车系列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载配件类型列表
        /// </summary>
        private async Task LoadCarPartsTypeListAsync()
        {
            try
            {
                var response = await HttpHelper<List<RepCarPartsType>>.GetAsync(ApiUrl.QueryCarPartsTypeList);
                if (response?.Code == StatusCodeEnum.OK && response.Data != null)
                {
                    RepCarPartsTypeList.Clear();
                    foreach (var item in response.Data)
                    {
                        RepCarPartsTypeList.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError($"加载配件类型列表失败: {ex.Message}");
            }
        }
        #endregion

        #region 数据编辑属性

         
        /// <summary>
        /// 当前配件
        /// </summary>
        public RepCarParts CurrentCarParts
        {
            get => _currentCarParts;
            set { _currentCarParts = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 车系列表
        /// </summary>
        public ObservableCollection<RepVehicleSeries> RepVehicleSeriesList
        {
            get => _repVehicleSeriesList;
            set { _repVehicleSeriesList = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 配件类型列表
        /// </summary>
        public ObservableCollection<RepCarPartsType> RepCarPartsTypeList
        {
            get => _repCarPartsTypeList;
            set { _repCarPartsTypeList = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 配件名称
        /// </summary>
        public string? Name
        {
            get => CurrentCarParts?.Name;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.Name = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 英文名称
        /// </summary>
        public string? EnglishName
        {
            get => CurrentCarParts?.EnglishName;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.EnglishName = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 配件编码
        /// </summary>
        public string? Code
        {
            get => CurrentCarParts?.Code;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.Code = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 车系ID
        /// </summary>
        public string? VehicleSeriesId
        {
            get => CurrentCarParts?.VehicleSeriesId;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.VehicleSeriesId = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 配件类型ID
        /// </summary>
        public string? CarPartsTypeId
        {
            get => CurrentCarParts?.CarPartsTypeId;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.CarPartsTypeId = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime? StartingDate
        {
            get => CurrentCarParts?.StartingDate;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.StartingDate = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime? EndingDate
        {
            get => CurrentCarParts?.EndDate;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.EndDate = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 图片
        /// </summary>
        public string? Image
        {
            get => CurrentCarParts?.Image;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.Image = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 自定义字段1
        /// </summary>
        public string? CustomField1
        {
            get => CurrentCarParts?.CustomFields1;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.CustomFields1 = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 自定义字段2
        /// </summary>
        public string? CustomField2
        {
            get => CurrentCarParts?.CustomFields2;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.CustomFields2 = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 自定义字段3
        /// </summary>
        public string? CustomField3
        {
            get => CurrentCarParts?.CustomFields3;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.CustomFields3 = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 自定义字段4
        /// </summary>
        public string? CustomField4
        {
            get => CurrentCarParts?.CustomFields4;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.CustomFields4 = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 自定义字段5
        /// </summary>
        public string? CustomField5
        {
            get => CurrentCarParts?.CustomFields5;
            set
            {
                if (CurrentCarParts != null)
                {
                    CurrentCarParts.CustomFields5 = value;
                    OnPropertyChanged();
                }
            }
        }

        private string? description;
        /// <summary>
        /// 描述
        /// </summary>
        public string? Description
        {
            get => description;
            set => SetProperty(ref description, value);
        }
        #endregion

        #region 提交，重置

        /// <summary>
        /// 提交数据
        /// </summary>
        protected override async Task SubmitAsync()
        {
            try
            {
                // 数据验证
                if (string.IsNullOrWhiteSpace(Name))
                {
                    ShowWarning("请输入配件名称");
                    return;
                }

                if (string.IsNullOrWhiteSpace(Code))
                {
                    ShowWarning("请输入配件编码");
                    return;
                }

                if (string.IsNullOrWhiteSpace(VehicleSeriesId))
                {
                    ShowWarning("请选择车系");
                    return;
                }

                if (string.IsNullOrWhiteSpace(CarPartsTypeId))
                {
                    ShowWarning("请选择配件类型");
                    return;
                }

                IsLoading = true;
                if (string.IsNullOrEmpty(_id))
                {
                    // 新增
                    var res = await HttpHelper<int>.PostAsync(ApiUrl.AddCarParts, CurrentCarParts);
                    HandleApiResponse(res, "添加成功", "添加失败");
                }
                else
                {
                    // 修改
                    var res = await HttpHelper<int>.PutAsync(ApiUrl.UpdateCarParts, CurrentCarParts);
                    HandleApiResponse(res, "修改成功", "修改失败");
                }
            }
            catch (Exception ex)
            {
                ShowError($"保存失败: {ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            _currentCarParts = new RepCarParts();
            OnPropertyChanged(nameof(Name));
            OnPropertyChanged(nameof(Code));
            OnPropertyChanged(nameof(Description));
            OnPropertyChanged(nameof(VehicleSeriesId));
            OnPropertyChanged(nameof(CarPartsTypeId));
        }
        #endregion
    }
}